﻿namespace LogManager.Gui
{
    using LogManager.Core.Infrastructure.Logging;
    using LogManager.Gui.AppStart;
    using LogManager.Gui.ViewModels;
    using LogManager.Utils.Unity;
    using System;
    using System.Diagnostics;
    using System.Windows;
    using System.Windows.Threading;
    using Microsoft.Practices.Unity;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private DI _containerWiring;

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            DispatcherUnhandledException += AppDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;

            _containerWiring = DI.Instance;
            _containerWiring.SetUp(AopBoot.Configure);

            var mainViewModel = DI.Container.Resolve<IMainViewModel>();
            var mainView = ((Window)mainViewModel.View);
            mainView.Show();

            if (e.Args.Length == 0)
            {
                mainViewModel.OpenDefault();
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            _containerWiring.Dispose();
        }


        private void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            HandleException(e.Exception, false);
            e.Handled = true;
        }

        private static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception, e.IsTerminating);
        }

        private static void HandleException(Exception e, bool isTerminating)
        {
            if (e == null) { return; }

            Trace.TraceError(e.ToString());

            if (!isTerminating)
            {
                Log.Logger.AddError("Error : " + e.Message, e.StackTrace);
                //throw e;
                // MessageBox.Show(e.ToString(), ApplicationInfo.ProductName, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
